#!/bin/bash

# Docker构建脚本
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 默认值
IMAGE_NAME="nest-base"
TAG="latest"
BUILD_TYPE="production"

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--tag)
            TAG="$2"
            shift 2
            ;;
        -n|--name)
            IMAGE_NAME="$2"
            shift 2
            ;;
        --dev)
            BUILD_TYPE="development"
            shift
            ;;
        -h|--help)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  -t, --tag TAG     镜像标签 (默认: latest)"
            echo "  -n, --name NAME   镜像名称 (默认: nest-base)"
            echo "  --dev             构建开发环境镜像"
            echo "  -h, --help        显示帮助信息"
            exit 0
            ;;
        *)
            print_error "未知选项: $1"
            exit 1
            ;;
    esac
done

print_message "开始构建Docker镜像..."
print_message "镜像名称: $IMAGE_NAME"
print_message "标签: $TAG"
print_message "构建类型: $BUILD_TYPE"

# 检查Docker是否运行
if ! docker info > /dev/null 2>&1; then
    print_error "Docker未运行，请启动Docker服务"
    exit 1
fi

# 构建镜像
if [ "$BUILD_TYPE" = "development" ]; then
    print_message "构建开发环境镜像..."
    docker build --target builder -t "${IMAGE_NAME}:${TAG}-dev" .
else
    print_message "构建生产环境镜像..."
    docker build -t "${IMAGE_NAME}:${TAG}" .
fi

# 检查构建结果
if [ $? -eq 0 ]; then
    print_message "镜像构建成功!"
    print_message "镜像ID: $(docker images -q ${IMAGE_NAME}:${TAG})"
    
    # 显示镜像信息
    echo ""
    print_message "镜像信息:"
    docker images "${IMAGE_NAME}:${TAG}"
else
    print_error "镜像构建失败!"
    exit 1
fi 